<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Requests\LuodiyeMobileRequest;
use App\Http\Requests\SendMessageRequest;
use App\LuodiyeMobile;
use App\model\VerifyCode;
use App\Repository\ToutiaoRepository;


class SendMessageController extends Controller
{
    protected $toutiaoRepository;
    public function __construct(ToutiaoRepository $toutiaoRepository)
    {
        $this->toutiaoRepository = $toutiaoRepository;
    }

    public function send(SendMessageRequest $request)
    {
        $mobile = $request->input('mobile');
        $sms = app('sms');
        $code = rand(1000, 9999);
        $verifyCode = VerifyCode::where('account', $mobile)->first();
        if ($verifyCode) {
            $time = $verifyCode->updated_at ?? $verifyCode->created_at;
            if (strtotime(now()) - strtotime($time) < 60) {
                throw new ApiException('短信发送太频繁');
            }

        } else {
            $verifyCode = new VerifyCode();
            $verifyCode->account = $mobile;
        }
        try {
            $sms->send($mobile, [
                # 'template' => 'SMS_113155005',
                'template' => 'SMS_194055821',
                'data' => [
                    'code' => $code
                ],
            ]);
        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {

            throw  new ApiException('短信发送失败');

        }
        $verifyCode->verify_code_num = $code;
        $verifyCode->save();
        return response()->json([
            'code' => 0,
            'data' => '短信发送成功',
        ]);
    }
    public function save(LuodiyeMobileRequest  $request){
        $mobile=$request->input('mobile');
        $code=$request->input('code');
        $verifyCode = VerifyCode::where('account', $mobile)->first();
        if ($verifyCode) {
            $time = $verifyCode->updated_at ?? $verifyCode->created_at;
            if ($code != $verifyCode->verify_code_num) {
                throw  new ApiException('验证码不正确');
            }
            if (strtotime(now()) - strtotime($time) > 600) {
                throw new ApiException('验证码已过期');
            }
        }else{
            throw new ApiException('请输入验证码');
        }
        $clikid = $request->input('clikid');
      $luodiye=  new LuodiyeMobile();
      $luodiye->mobile=$request->input('mobile');
      $luodiye->luodiye_id=$request->input('luodiye_id');
      $luodiye->save();
      if ($clikid){
          try {
              $aa= $this->toutiaoRepository->callback('form',$request->input('clickid'));//表单
          }catch (\Exception $exception){

          }

      }

      return response()->json([
          'code'=>0,
          'data'=>'保存成功'
      ]);
    }
}
